//
//  LeaderCommitWorkSummaryViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/20.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "LeaderCommitWorkSummaryViewController.h"
#import "WorkSummaryCommentCell.h"

NSString *const LeaderCommitWorkSummaryViewControllerInfoParamKey = @"LeaderCommitWorkSummaryViewControllerInfoParamKey";

@interface LeaderCommitWorkSummaryViewController ()<XUIGroupTableViewDelegate,XUIGroupTableViewDataSource,UITextViewDelegate,XUIButtonDelegate>
{
    RSWDataOperation *_manager;
    NSMutableArray *_datas;
    
    XUIGroupTableView *_gtable;
    WorkSummaryList *_workSummaryList;
    
    XUITextView *_commentContentTextView;
    UITextView *_textInputViewCell;
    
    XUIButton *_commentBtn;
}
@end

@implementation LeaderCommitWorkSummaryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    [self setBackNavigateItemTitle:@"领导点评"];
    
    [self initVariable];
    [self initUI];
    
    [_manager getWorkSummaryCommentById:_workSummaryList.workSummaryId isView:YES completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [self requestComplete:nil result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _datas = [NSMutableArray new];
    
    _workSummaryList = self.param[LeaderCommitWorkSummaryViewControllerInfoParamKey];
    
    [self addMainThreadObserverWithDictionarySelector:@{RSWDataOperationWorkSummaryCommentNotification:
                                                            @"observerRSWDataOperationWorkSummaryCommentNotification:"
                                                        }];
    [self addKeyboardObserver];
}

- (void)initUI
{
    _gtable = [[XUIGroupTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    _gtable.backgroundColor = [[UITableView appearance] backgroundColor];
    _gtable.delegate = self;
    _gtable.dataSource = self;
    
    [self.view addSubview:_gtable];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
    [self removeObserver];
}

-(void)requestComplete:(XMSDataOperationManager *)dom result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                 if (output != nil)
                 {
                     [_datas removeAllObjects]; 
                     [_datas addObjectsFromArray:output];
                 }
                 
                 [_gtable reloadData];
                 
                 break;
             }
             default:
             {
                 break;
             }
         }
     }];
}

#pragma mark --
#pragma mark -- XUIGroupTableViewDelegate XUIGroupTableViewDataSource
- (NSUInteger)numberOfGroupsInGroupTableView:(XUIGroupTableView *)groupTableView
{
    return 2 + _datas.count;
}

- (NSUInteger)groupTableView:(XUIGroupTableView *)groupTableView numberOfRowsInGroup:(NSInteger)group
{
    if(group ==0)
        return 3;
    return 1;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        CGSize s = [NSString charSizeWithFont:[UIFont systemFontOfSize:16]];
        CGFloat width = groupTableView.width - 10 - 4*s.width - 10 - 10;
        if(indexPath.row == 0)
        {
            CGFloat height = [_workSummaryList.title wrapStringSizeWithFont:[UIFont systemFontOfSize:16] forWidth:width].height;
            if(height < 80)
                height = 80;
            
            return height;
        }
        else if(indexPath.row == 1)
        {
            NSString *text = [NSString stringWithFormat:@"%@(%@)", _workSummaryList.createUser,[_workSummaryList.createTime toStringDate:NSDateFormatByyMdHm]];
            CGFloat height = [text wrapStringSizeWithFont:[UIFont systemFontOfSize:16] forWidth:width].height;
            if(height < 80)
                height = 80;
            return height;
        }
        else if(indexPath.row == 2)
        {
            CGFloat height = [_workSummaryList.content wrapStringSizeWithFont:[UIFont systemFontOfSize:16] forWidth:width].height;
            if(height < 150)
                height = 150;
            return height;
        }
    }
    else if(indexPath.section == 1)
        return 54;
    else
    {
        WorkSummaryCommentInfo * l = _datas[indexPath.section - 2];
        if(l != nil)
        {
            CGFloat height = [WorkSummaryCommentCell caleHeight:groupTableView.width content:l.commentContent];
            return height;
        }
    }
    
    return 44;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForHeaderInGroup:(NSInteger)group
{
    return 10;
}

-(UIEdgeInsets)groupTableView:(XUIGroupTableView *)groupTableView setSeparatorInsetForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return UIEdgeInsetsMake(0, 50, 0, 0);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (XUIGroupTableViewCell *)groupTableView:(XUIGroupTableView *)groupTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [self groupTableView:groupTableView heightForRowAtIndexPath:indexPath];
    
    XUIGroupTableViewCell *cell = [[XUIGroupTableViewCell alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(indexPath.section == 0)
    {
        CGSize s = [NSString charSizeWithFont:[UIFont systemFontOfSize:16]];
        
        UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, s.width * 4, s.height)];
        l.backgroundColor = [UIColor clearColor];
        l.font = [UIFont systemFontOfSize:16];
        l.textAlignment = NSTextAlignmentRight;
        l.textColor = [UIColor grayColor];
        l.centerY = height/2;
        [cell.contentView addSubview:l];
        
        UILabel *textField = [[UILabel alloc]initWithFrame:CGRectMake(l.right + 10, 0, groupTableView.width - 10 - l.width - 10 - 10 , height)];
        textField.font = [UIFont systemFontOfSize:16];
        textField.textColor = [UIColor grayColor];
        textField.numberOfLines = 0;
        textField.centerY = height/2;
        [cell.contentView addSubview:textField];
        
        switch(indexPath.row)
        {
            case 0:
            {
                l.text = @"标题";
                textField.text = _workSummaryList.title;
                
                break;
            }
            case 1:
            {
                l.text = @"记录人";
                textField.text = [NSString stringWithFormat:@"%@(%@)", _workSummaryList.createUser,[_workSummaryList.createTime toStringDate:NSDateFormatByyMdHm]];
                
                break;
            }
            case 2:
            {
                l.text = @"内容";
                textField.text = _workSummaryList.content;
                
                break;
            }
        }
        
        return cell;
    }
    else if(indexPath.section == 1)
    {
        CGFloat width = groupTableView.width - 10 - 10 - 40 - 10;
        _commentContentTextView = [[XUITextView alloc]initWithFrame:CGRectMake(0, 0, width, height - 10 - 10)];
        _commentContentTextView.delegate = self;
        _commentContentTextView.textInputMaxLength = 50;
        _commentContentTextView.hiddenDoneButton = NO;
        _commentContentTextView.placeHolder = @"请输入评语内容";
        _commentContentTextView.font = [UIFont systemFontOfSize:16];
        _commentContentTextView.left = 10;
        _commentContentTextView.centerY = height/2;
        
        _commentContentTextView.layer.borderColor = UIColor.grayColor.CGColor;
        _commentContentTextView.layer.borderWidth = 1;
        _commentContentTextView.layer.cornerRadius = 6;
        _commentContentTextView.layer.masksToBounds = YES;
        _commentContentTextView.alpha = 0.5;
        
        [cell addSubview:_commentContentTextView];
        
        _commentBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeLeftHeadImage delegate:self];
        _commentBtn.size = CGSizeMake(40, 20);
        [_commentBtn SetTitleColor:[UIColor colorWithHex:mcrmSAASUISkinColorTextStyle25B6EDColor]];
        [_commentBtn SetFont:[UIFont systemFontOfSize:16]];
        [_commentBtn SetTitle:@"提交"];
        _commentBtn.delegate = self;
        _commentBtn.centerY = height/2;
        _commentContentTextView.backgroundColor = [UIColor clearColor];
        
        _commentBtn.left = _commentContentTextView.right + 10;
        
        [cell addSubview:_commentBtn];
        
        return cell;
    }
    else
    {
        WorkSummaryCommentInfo * l = _datas[indexPath.section - 2];
        
        if(l != nil)
        {
            WorkSummaryCommentCell *wcell = [[WorkSummaryCommentCell alloc] initWithFrame:CGRectMake(0, 0, groupTableView.width, height)];
            wcell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            wcell.szTag = l.workSummaryCommentId;
            wcell.createUser = l.createUser;
            wcell.createTime = [l.createTime toStringDate:NSDateFormatByyMdHm];
            wcell.commentContent = l.commentContent;
            
            return wcell;
        }
    }
    
    return cell;
}

#pragma mark --
#pragma mark -- keyBoard
- (BOOL)keyboardDidShow:(NSNotification *)noti
{
    BOOL bResult = [super keyboardDidShow:noti];
    if (YES == bResult)
    {
        _gtable.height -= self.keyboardOffSet;
        
        if (_textInputViewCell != nil)
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
           
            [_gtable scrollToIndexPath:indexPath animated:YES];
        }
    }
    return bResult;
}

-(BOOL)keyboardWillHide:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillHide:noti];
    if(YES == bResult)
    {
        _gtable.height += self.keyboardOffSet;
    }
    return bResult;
}

-(void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    _gtable.height += changeSize;
}

#pragma mark --
#pragma mark -- UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    _textInputViewCell = textView;
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    _textInputViewCell = nil;
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    [UIViewController closeKeyBoard];
    
    if(btn == _commentBtn)
    {
        if([self submit] == NO)
            return;
        
        WorkSummaryInfo *modelInfo = [WorkSummaryInfo emptyWorkSummaryInfo];
        modelInfo.workSummaryId = _workSummaryList.workSummaryId;
        
        NSString *commentContent = [_commentContentTextView.text copy];

        [_manager commentWorkSummary:modelInfo commentContent:commentContent completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
         {
             [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
              {
                  switch (nResult)
                  {
                      case YES:
                      {
                          if(bReslut == YES)
                          {
                             
                          }
                          else
                          {
                              if(error.domain.length > 0)
                                  [UIAlertView showErrorMsg:error.domain];
                              else
                                  [UIAlertView showErrorMsg:@"提交失败"];
                          }
                          
                          break;
                      }
                      default:
                      {
                          [UIAlertView showErrorMsg:@"提交失败"];
                          break;
                      }
                  }
              }];
         }];
    }
}

-(BOOL)submit
{
    if(_commentContentTextView.text.length <= 0)
    {
        [UIAlertView showInfoMsg:@"评语内容不能为空"];
        return NO;
    }
    
    return YES;
}

#pragma mark --
#pragma mark -- observer

-(void)observerRSWDataOperationWorkSummaryCommentNotification:(NSNotification*)noti
{    
    [_manager getWorkSummaryCommentById:_workSummaryList.workSummaryId isView:YES completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [self requestComplete:nil result:nResult output:list error:error];
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
